package com.dayaokeji.rhythmschoolstudent.client.common.seat;

import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;

import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.Page;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.MeetingApi;
import com.dayaokeji.server_api.domain.MeetingInfo;
import com.qfdqc.views.seattable.SeatTable;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import retrofit2.Call;

/**
 * 显示座位
 */
public class ShowSeatActivity extends BaseActivity {

    /**
     * 用户座位号
     */
    public static final String EXTRA_USER_SEAT = "user_seat";
    /**
     * 座位排布字符串
     */
    public static final String EXTRA_ROOM_ID = "room_id";


    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.seatView)
    SeatTable seatView;
    @BindView(R.id.ll_seat_opt)
    LinearLayout llSeatOpt;

    private String userSeat;
    private String roomId;

    private static final MeetingApi meetingApi = ApiUtils.getApi(MeetingApi.class);
    private Call<ServerResponse<Page<MeetingInfo>>> meetingInfoCall;
    private String universityId;

    private int mSeatRowNum;
    private int mSeatColumnNum;
    /**
     * 用户座位座次 ， [0] = row [1] = column
     */
    private int[] userSeatArray = new int[2];

    private int userRow;
    private int userColumn;
    private int realUserColumn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_seat);
        setSupportActionBar(toolbar);

        userSeat = getIntent().getStringExtra(EXTRA_USER_SEAT);
        roomId = getIntent().getStringExtra(EXTRA_ROOM_ID);
        universityId = String.valueOf(UserUtils.getUserInfo().getUniversityId());

        if (TextUtils.isEmpty(userSeat) || TextUtils.isEmpty(roomId)) {
            ToastUtils.warning(R.string.data_incorrect);
            return;
        }

        init();
    }

    private void init() {
        if (!TextUtils.isEmpty(userSeat)) {
            userSeatArray = getUserSeat(userSeat);
            userRow = userSeatArray[0]-1;
            userColumn = userSeatArray[1];

            llSeatOpt.setVisibility(View.GONE);
        }
        getData();
    }


    private void getData() {
        meetingInfoCall = meetingApi.meetingInfo(roomId,universityId,1,1);
        meetingInfoCall.enqueue(new ServerCallback<Page<MeetingInfo>>(this,"加载中...") {
            @Override
            public void onResponse(boolean success, ServerResponse<Page<MeetingInfo>> response) {
                if (success) {
                    List<MeetingInfo> meetingInfos = response.getBody().getList();
                    if (meetingInfos != null && meetingInfos.size() >0) {
                        MeetingInfo meetingInfo = meetingInfos.get(0);
                        if (meetingInfo != null) {
                            if (toolbar != null) {
                                toolbar.setTitle(meetingInfo.getName());
                            }
                            String seat = meetingInfo.getSeat();
                            char[][] splitSeat = splitSeat(seat);
                            if (splitSeat != null) {
                                realUserColumn = getUserColumn(splitSeat);
                                setSeatTableView(splitSeat);
                            }
                        }

                    }
                }
            }
        });
    }

    /**
     * 将座位排布字符串拆装成二维字符数组
     *
     * @param seat
     * @return
     */
    private char[][] splitSeat(String seat) {
        if (TextUtils.isEmpty(seat)) {
            return null;
        }
        String[] seatRows = seat.split("\r\n");
        mSeatRowNum = seatRows.length;
        mSeatColumnNum = seatRows[0].length();
        if (mSeatRowNum > 0 && mSeatColumnNum > 0) {
            char[][] seatArray = new char[mSeatRowNum][mSeatColumnNum];

            for (int i = 0; i < seatRows.length; i++) {
                String seatRow = seatRows[i];
                char[] chars = seatRow.toCharArray();
                for (int j = 0; j < chars.length; j++) {
                    try{
                        seatArray[i][j] = chars[j];
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return seatArray;
        }
        return null;
    }

    /**
     * 设置排座View
     * @param seatArray
     */
    private void setSeatTableView(final char[][] seatArray) {
        seatView.setData(mSeatRowNum, mSeatColumnNum);
        seatView.setChecked(false);
        seatView.setMeeting(true);
        seatView.setSeatChecker(new SeatTable.SeatChecker() {
            @Override
            public boolean isValidSeat(int row, int column) {

                if (seatArray != null) {
                    char c = seatArray[row][column];
                    if (c == '+') {
                        return false;
                    } else if (c == '@') {
                        return true;
                    }
                }
                return false;
            }

            @Override
            public boolean isSold(int row, int column) {
                if (userSeatArray.length > 0) {
                    if (row == userRow) {
                        if (realUserColumn != -1) {
                            if (column == realUserColumn) {
                                return true;
                            } else {
                                return false;
                            }
                        }
                    }
                }else{
                    ToastUtils.warning("未安排座次");
                }
                return false;
            }

            @Override
            public void checked(int row, int column) {

            }

            @Override
            public void unCheck(int row, int column) {

            }

            @Override
            public String[] checkedSeatTxt(int row, int column) {
                return new String[]{userRow+"排"+userColumn+"座"};
            }
        });


    }

    /**
     * 正则解析用户座位座次
     *
     * @param userSeat
     * @return [0] = row  [1] = column
     */
    private int[] getUserSeat(String userSeat) {
        int[] userSeatArray = new int[2];
        String rgx = "(\\d+)([\\u4e00-\\u9fa5])(\\d+)([\\u4e00-\\u9fa5])";
        int row = 0;
        int column = 0;
        Pattern pattern = Pattern.compile(rgx);
        Matcher matcher = pattern.matcher(userSeat);
        if (matcher.find()) {
            row = Integer.valueOf(matcher.group(1));
            column = Integer.valueOf(matcher.group(3));
        }

        userSeatArray[0] = row;
        userSeatArray[1] = column;

        return userSeatArray;
    }

    /**
     * 得到用户实际的座位数
     * @param splitSeat
     * @return
     */
    private int getUserColumn(char[][] splitSeat) {
        int index = 0 ;
        char[] chars = splitSeat[userRow];
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '@') {
                index++;
            }
            if (index == userColumn){
                return i;
            }
        }
        return -1;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (meetingInfoCall != null) {
            meetingInfoCall.cancel();
        }
    }
}
